/*
 * Copyright 2014 Soichiro Kashima
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tsingteng.cosfun.ui.mine.tab;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.nineoldandroids.view.ViewHelper;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.DialogListener;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.PlayBean;
import com.tsingteng.cosfun.bean.VidePersonBean;
import com.tsingteng.cosfun.bean.VideoBean;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.cosfun.PlayActivity;
import com.tsingteng.cosfun.ui.cosfun.ShareFragment;
import com.tsingteng.cosfun.ui.cosfun.contract.PersonWorkContract;
import com.tsingteng.cosfun.ui.cosfun.presenter.PersonWorkPresenter;
import com.tsingteng.cosfun.ui.message.geneal.PlayVideoAdapter;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.PersonTabBaseFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.ui.mine.adapter.CommonAdapter;
import com.tsingteng.cosfun.utils.DialogUtil;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.ShareUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;
import com.tsingteng.cosfun.widget.ObservableListView;
import com.tsingteng.cosfun.widget.dialog.BottomListDialog;
import com.tsingteng.cosfun.widget.flexible.CosfunListView;
import com.tsingteng.cosfun.widget.flexible.ScrollUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.tsingteng.cosfun.ui.mine.HomeMineFragment.USERID;

/**
 * author :zhikuan
 * Date:18-8-20
 */
public class PersonTabListParaGraphFragment extends PersonTabBaseFragment<ObservableListView> implements PersonWorkContract.IPersonWorkrView, ShareUtils.ShareListener, CosfunListView.GListViewListener
        , DialogListener {

    private PersonWorkPresenter personWorkPresenter;
    private int pageNo = 0;
    private long userId;
    private String showType = "1"; //1表示自己的作品
    private CommonAdapter<PlayBean.PlayListBean> mAdapter;
    private BottomListDialog dialog;
    private TextView emptyView;
    ObservableListView listView;
    private List<VideoBean> list = new ArrayList<>();
    private boolean mIsRefreshing = false;

    public static PersonTabListParaGraphFragment newInstance(String type) {
        PersonTabListParaGraphFragment hf = new PersonTabListParaGraphFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        hf.setArguments(args);
        return hf;
    }

    private int flexibleSpaceImageHeight;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_person_baselsit_layout, container, false);
        emptyView = view.findViewById(R.id.text_empty);
        listView = (ObservableListView) view.findViewById(R.id.scroll);
        listView.setOnTouchListener((view1, motionEvent) -> {
            if (mIsRefreshing) {
                return true;
            } else {
                return false;
            }
        });
        flexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.dp_300);


        View paddingView = new View(getContext());
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, flexibleSpaceImageHeight);
        paddingView.setLayoutParams(layoutParams);
        paddingView.setClickable(false);
        listView.setPullRefreshEnable(false);
        listView.setPullLoadEnable(true);
        listView.setText(getResources().getString(R.string.loading));
        listView.setCListViewListener(this);
        listView.addHeaderView(paddingView);
        personWorkPresenter = new PersonWorkPresenter(this);
        mAdapter = new CommonAdapter<PlayBean.PlayListBean>(getContext(), null, R.layout.item_person_play_adapter) {
            @Override
            public void convert(ViewHolder helper, PlayBean.PlayListBean item, int positon) {
                CircleImageView headerView = helper.getView(R.id.iv_header);
                TextView name = helper.getView(R.id.tv_name);
                TextView operator = helper.getView(R.id.tv_operator);
                TextView tvContent = helper.getView(R.id.tv_content);
                TextView greatNum = helper.getView(R.id.tv_great_num);
                TextView videoNum = helper.getView(R.id.tv_video_count);
                TextView commentNum = helper.getView(R.id.tv_comment_num);
                TextView shareNum = helper.getView(R.id.tv_share_num);
                ImageView ivGreat = helper.getView(R.id.iv_great);
                ImageView iv_more = helper.getView(R.id.iv_more);

                setText(name, item.getNickName());
                setText(operator, item.getOperatorLabel());
                setText(tvContent, item.getContent());
                setText(greatNum, item.getPraiseCount());
                setText(commentNum, item.getCommentCount());
                setText(shareNum, item.getForwardCount());
                if (TextUtils.equals(item.getVideoCount(), "0")) {
                    videoNum.setVisibility(View.GONE);
                } else {
                    videoNum.setVisibility(View.VISIBLE);
                    setText(videoNum, "翻拍视频 " + item.getVideoCount() + "个");
                }
                ImageUtils.LoadImage(getContext(), item.getImage(), headerView);

                if (item.getPraiseStatus() == 0) {
                    ivGreat.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.great_icon));
                } else {
                    ivGreat.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.great_pink_icon));
                }

                MyRecycleView mRv = helper.getView(R.id.rv_video);
                mRv.isCanRefresh(false);
                mRv.setLayoutManager(new GridLayoutManager(getActivity(), 4));
                PlayVideoAdapter playVideoAdapter = new PlayVideoAdapter();
                mRv.setAdapter(playVideoAdapter);
                List<VideoBean> data = item.getVideoInfos().getData();
                if (list != null) {
                    list.clear();
                } else {
                    list = new ArrayList<>();
                }
                if (data.size() > 4) {
                    for (int i = 0; i < 4; i++) {
                        list.add(data.get(i));
                    }
                } else {
                    list.addAll(data);
                }
                playVideoAdapter.addData(list);
                playVideoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        Intent intent = new Intent(getContext(), PlayActivity.class);
                        intent.putExtra("type", 1);
                        intent.putExtra("id", item.getId());
                        intent.putExtra("position", position);
                        getActivity().startActivity(intent);
                    }
                });
                //更多
                helper.getView(R.id.iv_more).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        dialog = new BottomListDialog(getContext());
                        if ("1".equals(showType) || item.getProfileId() == LogonUtils.getProFildId()) {//自己
                            List<String> moreList = new ArrayList<>();
                            moreList.add("删除");
                            dialog.setList(moreList);
                        } else {
                            List<String> moreList = new ArrayList<>();
                            moreList.add("举报");
                            moreList.add("不感兴趣");
                            dialog.setList(moreList);
                        }
                        dialog.setOnClickBottomListListener(new BottomListDialog.OnClickBottomListListener() {
                            @Override
                            public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
                                switch (list.get(position)) {
                                    case "举报":
                                        Navigate.startReportList(getContext(), 5, item.getId());
                                        dialog.dissMiss();
                                        break;
                                    case "不感兴趣":
//                                            if (item.getPraiseStatus() == 1) {
//                                                personWorkPresenter.getPraiseOrNotData("-1", String.valueOf(item.getId()), "0", positon);
//                                            } else {
//                                                personWorkPresenter.getPraiseOrNotData("1", String.valueOf(item.getId()), "0", positon);
//                                            }
                                        personWorkPresenter.getAddNotLikePlay(item.getId() + "", positon);
                                        dialog.dissMiss();
                                        break;
                                    case "删除":
                                        personWorkPresenter.getDelPlay(item.getId() + "", positon);
                                        dialog.dissMiss();
                                        break;
                                }
                            }

                            @Override
                            public void onClickBottom() {

                            }
                        });

                        dialog.show();
                    }
                });
                //关注
                RelativeLayout rl_guan_zhu = helper.getView(R.id.rl_guan_zhu);
                TextView tv_play_guan_zhu = helper.getView(R.id.tv_play_guan_zhu);
                int relationType = item.getRelationType();//缺少参数

                if (relationType == 0) {
                    tv_play_guan_zhu.setVisibility(View.VISIBLE);
                    tv_play_guan_zhu.setText("关注");
                    tv_play_guan_zhu.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_bg_white));
                    tv_play_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.black));
                } else if (relationType == 1) {
                    tv_play_guan_zhu.setVisibility(View.VISIBLE);
                    tv_play_guan_zhu.setText("已关注");
                    tv_play_guan_zhu.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_trank_bg));
                    tv_play_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.white));
                } else if (relationType == 2) {
                    tv_play_guan_zhu.setVisibility(View.VISIBLE);
                    tv_play_guan_zhu.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_pink_bg));
                    tv_play_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.color_found));
                    tv_play_guan_zhu.setText("互相关注");
                } else if (relationType == -1) {
                    tv_play_guan_zhu.setVisibility(View.INVISIBLE);
                }

                rl_guan_zhu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("关注".equals(tv_play_guan_zhu.getText())) {
                            personWorkPresenter.loginFollowFans(item.getProfileId() + "", positon);
                        } else {
                            personWorkPresenter.loginNoFollow(item.getProfileId() + "", positon);
                        }


                    }
                });
                //拍成剧
                helper.getView(R.id.iv_film_drama).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        VideoHelper.getIntence().starVideoShootToPlay(getActivity(), item.getId());
                    }
                });
                //点赞
                helper.getView(R.id.ll_great).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.getPraiseStatus() == 1) {
                            personWorkPresenter.getPraiseOrNotData("-1", String.valueOf(item.getId()), "0", positon);
                        } else {
                            personWorkPresenter.getPraiseOrNotData("1", String.valueOf(item.getId()), "0", positon);
                        }
                    }
                });
                //评论
//        helper.getView(R.id.ll_comment).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (onAdapterFunctionListener != null) {
//                    onAdapterFunctionListener.onCommentClick(item);
//                }
//            }
//        });
                //分享
                helper.getView(R.id.ll_share).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShareFragment shareFragment = ShareFragment.newInstance();
                        shareFragment.setLisenter(new ShareFragment.OnShareItemClickLisenter() {
                            @Override
                            public void share(SHARE_MEDIA share_media, int type) {
                                ShareUtils.getIntance().sharePlay(getActivity(), share_media, String.valueOf(item.getId()), item.getNickName(), item.getCommentCount(), item.getImage(), PersonTabListParaGraphFragment.this);
                            }

                            @Override
                            public void other(int type) {

                            }
                        });
                        shareFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
                    }
                });

                //头像
                headerView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int tag;
                        if (item.getRelationType() == -1) {
                            tag = 0;
                        } else {
                            tag = 1;
                        }
                        int profileId = item.getProfileId();
                        Bundle bundle = new Bundle();
                        bundle.putInt("tag", tag);
                        bundle.putInt("user_id", profileId);
                        TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
                    }
                });
                /**
                 * item
                 */
                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = item.getId();
                        String name = item.getNickName();
                        int profileId = item.getProfileId();
                        int relationType = item.getRelationType();
                        Navigate.startPlayDetails(getContext(), id, name, profileId, relationType);
                    }
                });

            }

        };
        listView.setAdapter(mAdapter);
        listView.setTouchInterceptionViewGroup((ViewGroup) view.findViewById(R.id.fragment_root));

        Bundle args = getArguments();
        if (args != null && args.containsKey(ARG_SCROLL_Y)) {
            final int scrollY = args.getInt(ARG_SCROLL_Y, 0);
            ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() {
                @SuppressLint("NewApi")
                @Override
                public void run() {
                    int offset = scrollY % flexibleSpaceImageHeight;
                    listView.setSelectionFromTop(0, -offset);
                }
            });
            updateFlexibleSpace(scrollY, view);
        } else {
            updateFlexibleSpace(0, view);
        }

        listView.setScrollViewCallbacks(this);

        updateFlexibleSpace(0, view);

        if (args != null && args.containsKey(TYPE)) {
            showType = args.getString(TYPE);
        }
        if (args != null && args.containsKey(USERID)) {
            userId = args.getLong(USERID);
        }

        refreshData();
        return view;
    }

    public void refreshData() {
        if (null == mAdapter){
            return;
        }
        mAdapter.clearData();
        pageNo = 1;
        Log.i("showType", showType);
        if ("1".equals(showType)) {
            personWorkPresenter.getParagraphList(userId, pageNo + "", Config.PAGE_SIZE + "");
        } else {
            personWorkPresenter.getParagraphLikeList(userId, pageNo + "", Config.PAGE_SIZE + "");
        }
    }

    public void setRefresh(boolean boo) {
        this.mIsRefreshing = boo;
    }

    public void refreshData(int id) {
        userId = id;
        if (null != mAdapter) {
            mAdapter.clearData();
        }
        pageNo = 1;
        Log.i("showType", showType);
        if (personWorkPresenter == null) return;
        if ("1".equals(showType)) {
            personWorkPresenter.getParagraphList(userId, pageNo + "", Config.PAGE_SIZE + "");
        } else {
            personWorkPresenter.getParagraphLikeList(userId, pageNo + "", Config.PAGE_SIZE + "");
        }
    }

    public void setText(TextView textView, String text) {
        if (textView != null && !text.isEmpty())
            textView.setText(text);
    }


    @Override
    public void getFollowResult(FollowBean followBean, int position) {
        long prodeId = mAdapter.getItem(position).getProfileId();
        String mNickName = mAdapter.getItem(position).getNickName();
        if (null == followBean) {
            @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
            String content = getResources().getString(R.string.comment_handle, mNickName);
            DialogUtil.getContentCommentDialog(getActivity(), content, prodeId, this);
            return;
        }
        if (followBean.getRelationShip() == null) {
            return;
        }
        mAdapter.getItem(position).setRelationType(followBean.getRelationType());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showParagraphData(PlayBean data) {
        setRefresh(false);
        listView.stopLoadMore();
        if (isAdded()) {
            listView.setText(getResources().getString(R.string.listview_footer_hint_normal));
        }
        if (data == null || data.getData() == null || data.getData().size() == 0) {
            if (isEmpty()) {
                emptyView.setVisibility(View.VISIBLE);
                if ("1".equals(showType)) {
                    emptyView.setText("TA还没有便当~");
                } else {
                    emptyView.setText("TA还没有喜欢的便当~");
                }
                listView.setFooterText("");
            } else {
                emptyView.setVisibility(View.GONE);
                listView.setFooterText("到底啦~");

            }
            return;
        }
//        if (data.getData().size() <= 10) {//不可下拉
//            listView.setFooterText("到底啦~");
//        }
        pageNo++;
        mAdapter.addData(data.getData());
        if (isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            emptyView.setText("TA还没有便当~");
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }

    private boolean isEmpty() {

        int count = mAdapter.getCount();
        if (count > 0) {//有数据
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void shoWorkData(VidePersonBean data) {

    }


    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }



    @SuppressWarnings("NewApi")
    @Override
    public void setScrollY(int scrollY, int threshold) {
        View view = getView();
        if (view == null) {
            return;
        }
        ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
        if (listView == null) {
            return;
        }
        View firstVisibleChild = listView.getChildAt(0);
        if (firstVisibleChild != null) {
            int offset = scrollY;
            int position = 0;
            if (threshold < scrollY) {
                int baseHeight = firstVisibleChild.getHeight();
                position = scrollY / baseHeight;
                offset = scrollY % baseHeight;
            }
            listView.setSelectionFromTop(position, -offset);
        }
    }

    @Override
    protected void updateFlexibleSpace(int scrollY, View view) {

        View listBackgroundView = view.findViewById(R.id.list_background);
        ViewHelper.setTranslationY(listBackgroundView, Math.max(0, -scrollY + flexibleSpaceImageHeight));
        List<android.support.v4.app.Fragment> listFragment = getActivity().getSupportFragmentManager().getFragments();
        for (int i = 0; i < listFragment.size(); i++) {
            android.support.v4.app.Fragment fragment = listFragment.get(i);
            if (fragment instanceof HomeMineFragment) {
                ((HomeMineFragment) fragment).onScrollChanged(scrollY, (ObservableListView) view.findViewById(R.id.scroll));

            }
        }
    }


    @Override
    public void onShareFinish() {

    }

    @Override
    public void onShareSuccess() {

    }

    @Override
    public void showPraiseResult(Integer data, int position) {
        int num = Integer.parseInt(mAdapter.getItem(position).getPraiseCount());
        if (data == 1) {
            num++;
            mAdapter.getItem(position).setPraiseStatus(1);
            mAdapter.getItem(position).setPraiseCount(num == 0 ? "0" : num + "");
            mAdapter.notifyDataSetChanged();
        } else {
//            num--;
//            mAdapter.getItem(position).setPraiseStatus(0);
//            mAdapter.getItem(position).setPraiseCount(num == 0 ? "0" : num + "");
            mAdapter.removeData(mAdapter.getItem(position));
        }
    }

    @Override
    public void ShowNotLiketResult(BaseDataBean<String> dataBean, int position) {
        if (dataBean.getStatus() == 200) {
            ToastUtils.showToast("已设置为不感兴趣");
            mAdapter.removeData(mAdapter.getItem(position));
        } else {
            ToastUtils.showToast(dataBean.getMsg());
        }
    }

    @Override
    public void showDelResult(BaseDataBean<String> dataBean, int position) {
        if (dataBean.getStatus() == 200) {
            ToastUtils.showToast("删除成功");
            mAdapter.removeData(mAdapter.getItem(position));
        } else {
            ToastUtils.showToast(dataBean.getMsg());
        }
    }

    @Override
    public void showCancelPullBlack(int data) {
        if (1 == data) {
            ToastUtils.showToast(getResources().getString(R.string.cancel_black_success));
        }
    }

    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        if ("1".equals(showType)) {
            personWorkPresenter.getParagraphList(userId, pageNo + "", Config.PAGE_SIZE + "");
        } else {
            personWorkPresenter.getParagraphLikeList(userId, pageNo + "", Config.PAGE_SIZE + "");
        }
    }

    @Override
    public void onDeleteItem(int index) {

    }

    @Override
    public void clickDialog(long workId) {
        personWorkPresenter.getCancelPullBlack(workId);
    }
}
